package com.xhwl.centiotdata.suppliersystem.bosiny;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.constant.BosinyConstant;
import com.xhwl.centiotdata.pojo.dto.bosiny.BosinyDeviceDTO;
import com.xhwl.centiotdata.pojo.dto.device.DeviceIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * Falcon.cao @Copyright (C), 2022, 兴海物联
 * Date: 2022/6/15 10:06
 * Description: 包信息
 */
@Slf4j
@Service
public class DeviceBosinyHandler {

    @Autowired
    private GeneralBosinyHandler generalBosinyHandler;

    public List<BosinyDeviceDTO> getDevicesSN(PedestrianIntegrationConfigDTO config) {
        JSONObject result = generalBosinyHandler.execute(config, null, BosinyConstant.NAME_LOCK_GET_SN, "");
        if ("0".equals(result.getString("code"))) {
            JSONArray array = result.getJSONObject("data").getJSONArray("lockSns");
            return array.toJavaList(BosinyDeviceDTO.class);
        }
        return Collections.emptyList();
    }

    // 获取门禁
    public List<BosinyDeviceDTO> pullDoor(DeviceIntegrationConfigDTO configDTO) {
        PedestrianIntegrationConfigDTO config = new PedestrianIntegrationConfigDTO();
        BeanUtils.copyProperties(configDTO, config);
        return getDevicesSN(config);
    }

    // 获取门禁在离线状态
    public List<BosinyDeviceDTO> pullDoorOnlineStatus(DeviceIntegrationConfigDTO configDTO) {
        PedestrianIntegrationConfigDTO config = new PedestrianIntegrationConfigDTO();
        BeanUtils.copyProperties(configDTO, config);
        List<BosinyDeviceDTO> devicesSN = getDevicesSN(config);

        for (BosinyDeviceDTO dto : devicesSN) {
            JSONObject params = new JSONObject();
            params.put(BosinyConstant.PARAM_CODE, dto.getSn());
            JSONObject object = generalBosinyHandler.execute(config, params, BosinyConstant.NAME_LOCK_GET, "1.0");
            dto.setOnline(object != null && object.containsKey("data") && object.getJSONObject("data").getIntValue("signalQuality") > 0);
        }
        return devicesSN;
    }

}
